package com.happy.ibidding.controller;

import com.happy.ibidding.bean.Bid;
import com.happy.ibidding.service.AskService;
import com.happy.ibidding.service.BidService;
import com.happy.ibidding.service.UserService;
import com.happy.ibidding.util.RandomUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("api/bid")
public class BidController {

    final private BidService bidService;

    final private UserService userService;

    final private AskService askService;

    public BidController(BidService bidService, UserService userService, AskService askService) {
        this.bidService = bidService;
        this.userService = userService;
        this.askService = askService;
    }


    @PostMapping
    public Bid bid(@RequestBody Bid bid) {
        bid.setId(null);
        bid.setBidId(RandomUtil.generateRandomId("bid-", ""));
        bid.setBidTime(System.currentTimeMillis());
        bid.setWin(false);
        bid.setWinTime(0);
        return this.bidService.save(bid);
    }

    @GetMapping("/all")
    public List<Bid> viewAll(@RequestParam(required = false) String askId, @RequestParam(required = false) String userId) {
        List<Bid> bidList = this.bidService.viewAll(askId, userId);

        bidList.parallelStream().forEach(each -> {
            each.setAsk(this.askService.view(each.getAskId()));
            each.setUser(this.userService.findUserByUserId(each.getUserId()));
        });
        return bidList;
    }


    @GetMapping("/delete/{mongodbId}")
    public void delete(@PathVariable  String mongodbId){
        this.bidService.deleteBid(mongodbId);
    }

}
